import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tiktok/video.dart';

class IndexWidget extends StatefulWidget {
  const IndexWidget({super.key});

  @override
  State<IndexWidget> createState() => _IndexWidgetState();
}

class _IndexWidgetState extends State<IndexWidget> {
  int topBarIndex = 4;
  int bottomBarIndex = 0;

  List<dynamic> data = [];

  @override
  void initState() {
    super.initState();

    getData();
  }

  void getData() async {
    try {
      var response = await Dio().get(
          'https://www.douyin.com/aweme/v1/web/tab/feed/?device_platform=webapp&aid=6383&channel=channel_pc_web&tag_id=&ug_source=&creative_id=&count=10&refresh_index=1&video_type_select=0&aweme_pc_rec_raw_data=%7B%22is_client%22:false%7D&globalwid=&version_code=170400&version_name=17.4.0&pull_type=0&cookie_enabled=true&screen_width=1920&screen_height=1080&browser_language=zh-CN&browser_platform=MacIntel&browser_name=Edge&browser_version=109.0.1518.70&browser_online=true&engine_name=Blink&engine_version=109.0.0.0&os_name=Mac%20OS&os_version=10.15.7&cpu_core_num=8&device_memory=8&platform=PC&downlink=2.1&effective_type=4g&round_trip_time=150&pc_client_type=1&msToken=ShQJMXaSKjPlGfbxMYEReFrJP8M0bZH5uzm38mDdWIj2YijeQ9mSm5vC4eZEPOTRT6empmQKmBbLeuM1BAC1unZhNXmU7nKYSziiHmqrZXUXce7bjT1wPPQPXVkOnkI=&X-Bogus=DFSzswVOeYGANe1ES4J-mN7TlqCh',
          options: Options(headers: {
            "authority": "www.douyin.com",
            "method": "GET",
            "scheme": "https",
            "accept": "*/*",
            "cookie":
                "ttwid=1%7C8rImVDchYwIEwy98gJM8QjHFp_OetWYYd1rgz_Edw3o%7C1675137937%7C9bf9642ad8ea010097ee2c2478c8cfc7bc59f7ed6227418e54a8360fed33330b; douyin.com; passport_csrf_token=4e89a2673a9f5ad765ae174c60ffb6cc; passport_csrf_token_default=4e89a2673a9f5ad765ae174c60ffb6cc; s_v_web_id=verify_ldjpvmye_ws1ZQ54y_kZPt_4Mdh_8awF_rCV7r79OWiP6; ttcid=2bdc616d5c9c4b0d94e5ba908f7a24fc27; VIDEO_FILTER_MEMO_SELECT=%7B%22expireTime%22%3A1675742767822%2C%22type%22%3A0%7D; strategyABtestKey=%221675137969.756%22; home_can_add_dy_2_desktop=%221%22; tt_scid=jm39uT54W0N5eatxTXdMZh522OhjuSn6dYMc7bqFMWYLs1RdYUYKuQPV8tzPRAoUb5d3; download_guide=%222%2F20230131%22; msToken=autZoCwzX-FQS0GfTNr-M4LXEo2OT6u_X8cMMS4vy1yF6gbT60adYhq9k0cuxa3uFaxOmRUQzBjl7Hc14wdO488ulXJrfhOgO7HYcYZHw83fJMHNkvwcekGJHgtNVYY=; msToken=ShQJMXaSKjPlGfbxMYEReFrJP8M0bZH5uzm38mDdWIj2YijeQ9mSm5vC4eZEPOTRT6empmQKmBbLeuM1BAC1unZhNXmU7nKYSziiHmqrZXUXce7bjT1wPPQPXVkOnkI=; __ac_nonce=063d89fd4009fec05f0c2; __ac_signature=_02B4Z6wo00f01hR7mQAAAIDBgK3CDinqvAYUW52AAObUwIR186k84o7x-p-elmROGM.vyLUMkt0f-pJzqf98H9sNrvxiyxDMr8ml7v9TMpUQ-dTObwu2pr7EmFiAHcXopwCvhioSNmVtm-Mtb9",
            "referer": "https://www.douyin.com/",
            "user-agent":
                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 Edg/109.0.1518.70"
          }));
      setState(() {
        data.addAll(response.data["aweme_list"]);
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: Container(
      color: Colors.black,
      child: Column(
        children: [
          Expanded(
            flex: 1,
            child: Stack(
              children: [
                PageView.builder(
                    onPageChanged: (value) {
                      if (value == data.length - 1) {
                        getData();
                      }
                    },
                    scrollDirection: Axis.vertical,
                    itemCount: data.length,
                    itemBuilder: (context, index) {
                      var videoWidget = VideoWidget(data[index]);
                      return videoWidget;
                    }),
                Positioned(
                  top: 0,
                  left: 0,
                  right: 0,
                  child: _buildTopBar(context),
                )
              ],
            ),
          ),
          _buildBottomBar()
        ],
      ),
    ));
  }

  Container _buildBottomBar() {
    return Container(
      padding: const EdgeInsets.only(bottom: 20, top: 10),
      height: 80,
      color: Colors.black,
      child: Row(
        children: [
          _buildBottomBarItem("首页", 0),
          _buildBottomBarItem("朋友", 1),
          Expanded(
            flex: 1,
            child: Center(
              child: Container(
                padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    border: Border.all(width: 3, color: Colors.white)),
                child: const Icon(
                  Icons.add,
                  size: 18,
                  color: Colors.white,
                ),
              ),
            ),
          ),
          _buildBottomBarItem("消息", 3),
          _buildBottomBarItem("我", 4),
        ],
      ),
    );
  }

  Widget _buildBottomBarItem(String title, int index) {
    return Expanded(
      flex: 1,
      child: GestureDetector(
        onTap: () => setState(() {
          bottomBarIndex = index;
        }),
        child: Text(
          title,
          textAlign: TextAlign.center,
          style: TextStyle(
              fontSize: 20,
              color: bottomBarIndex == index
                  ? Colors.white
                  : Colors.white.withOpacity(0.6)),
        ),
      ),
    );
  }

  Container _buildTopBar(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
            colors: [Colors.black.withOpacity(0.5), Colors.transparent],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter),
      ),
      padding: EdgeInsets.only(
          top: MediaQuery.of(context).padding.top,
          bottom: 20,
          left: 10,
          right: 10),
      child: Row(
        children: [
          Container(
              margin: const EdgeInsets.only(bottom: 8, right: 10),
              padding: const EdgeInsets.all(2),
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(20),
                  border: Border.all(width: 2, color: Colors.white)),
              child: const Icon(
                Icons.add,
                size: 14,
                color: Colors.white,
              )),
          Expanded(
            flex: 1,
            child: SingleChildScrollView(
                scrollDirection: Axis.horizontal,
                reverse: true,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    _buildTopBarItem("抗疫", 0),
                    _buildTopBarItem("探索", 1),
                    _buildTopBarItem("关注", 2),
                    _buildTopBarItem("商城", 3),
                    _buildTopBarItem("推荐", 4),
                  ],
                )),
          ),
          Container(
              margin: const EdgeInsets.only(bottom: 8, left: 10),
              child: SvgPicture.asset("assets/svg/search.svg")),
        ],
      ),
    );
  }

  Widget _buildTopBarItem(String title, int index) {
    return GestureDetector(
      onTap: (() => setState(() {
            topBarIndex = index;
          })),
      child: Column(
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16),
            child: Text(
              title,
              style: TextStyle(
                  color: topBarIndex == index
                      ? Colors.white
                      : Colors.white.withOpacity(0.6),
                  fontSize: topBarIndex == index ? 19 : 18),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(top: 4),
            width: 30,
            height: 2,
            color: topBarIndex == index ? Colors.white : Colors.transparent,
          )
        ],
      ),
    );
  }

  Future<List<dynamic>> readJsonFile(String filePath) async {
    String input = await rootBundle.loadString(filePath);
    var map = jsonDecode(input);
    return map['aweme_list'];
  }
}
